package com.life.wd.exception;

import com.life.wd.result.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CommonException.class)
    public ResponseEntity<Result> handleBusinessException(CommonException e) {
        // 返回包含错误码和错误信息的统一格式响应
        Result result = Result.error(e.getMessage());
        result.setCode(e.getCode()); // 设置自定义的错误码
        return new ResponseEntity<>(result, HttpStatus.valueOf(e.getCode())); // 根据异常的错误码设置HTTP状态码
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result> handleGeneralException(Exception e) {
        // 捕获其他未处理的异常，返回 500 错误码
        Result result = Result.error("系统异常");
        result.setCode(500);
        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
